package com.sumainfor.common.util;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sumainfor.common.NiuYunToken;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.entity.UploadResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author PuaChen
 * @Create 2018-05-26 21:47
 */

public class RemoteFileUpload {

    private static UploadManager UPLOAD_MANAGER;
    @Autowired
    private RedisUtils redisUtils;
    public static final String UPLOAD_TOKEN = "QiYun_UPDATE_TOKEN";
    private Logger logger = LoggerFactory.getLogger(getClass());

    public RemoteFileUpload(Zone zone) {
        if (zone == null) {
            throw new NullPointerException("构造初始配置出错：RemoteFileUpload");
        }
        Configuration cfg = new Configuration(zone);
        UPLOAD_MANAGER = new UploadManager(cfg);
    }

    private String getToken() {
        String token = redisUtils.get(UPLOAD_TOKEN);
        if (StringUtils.isBlank(token)) {
            //...生成上传凭证，然后准备上传
            String accessKey = NiuYunToken.QINIU_ACCESS_KEY;
            String secretKey = NiuYunToken.QINIU_SECRET_Key;
            String bucket = NiuYunToken.publicBucketname;
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            if (StringUtils.isBlank(upToken)) {
                throw new NullPointerException("获取Token失败");
            }
            token = upToken;
            redisUtils.set(UPLOAD_TOKEN, upToken, 3600);
        }
        return token;
    }

    public JsonResult<UploadResult> upload(File file) {
        if (StringUtils.isBlank(NiuYunToken.publicQiniuUrl)) {
            throw new NullPointerException("文件上传的URL地址常量没有初始化 在类Const中(FILE_ROOT_URL)");
        }

        if (file != null) {
            String newFileName = "新签合同-" + UUIDUtils.generateShortUuid() + ".pdf";
            String url = file.getAbsolutePath();
            UploadResult uploadResult;
            try {
                Response response = UPLOAD_MANAGER.put(url, newFileName, getToken());
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                logger.debug("上传成功返回的文件名是:{}", putRet.key);

                uploadResult = new UploadResult();
                uploadResult.setNewName(newFileName);
                String resultName = String.format("%s%s", NiuYunToken.publicQiniuUrl, URLEncoder.encode(putRet.key, "utf-8"));
                uploadResult.setAbsoluteUrl(resultName);
            } catch (QiniuException ex) {
                Response r = ex.response;
                logger.error(r.toString());
                try {
                    logger.error(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
                return JsonResult.error("上传出错");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                logger.error("URL 编码出现异常", e);
                return JsonResult.error("上传出错");
            } finally {
                if (file != null) {
                    file.delete();
                }
            }
            if (uploadResult != null) {
                return JsonResult.success(uploadResult);
            } else {
                return JsonResult.error("上传出错");
            }

        }
        return JsonResult.errorForEmpty();
    }
}
